<?php
/**
 * Created by PhpStorm.
 * User: 86158
 * Date: 2021/7/10
 * Time: 1:44
 */

namespace App\Http\Controllers\api\exam;


use App\Http\Controllers\api\base\BaseController;
use App\Http\Resources\exam\ExamPageResource;
use App\Http\Resources\exam\ExamQuestionDetailResource;
use App\Models\exams\Exam;
use App\Models\exams\ExamLog;
use App\Models\exams\ExamQuestion;
use App\Models\exams\Question;
use App\Models\exams\UserExam;
use App\Models\user\Collect;
use App\Services\exam\ExamService;
use Carbon\Carbon;
use Illuminate\Http\Request;

class ExamController extends BaseController
{
    /**
     * 试题列表
     * @param Request $request
     * @return mixed
     */
    public function examList(Request $request)
    {
        $type = $request->type;
        $data = Exam::where('status',1)
            ->where('type',$type)
            ->where('start_time','<=',Carbon::now())
            ->where('end_time','>=',Carbon::now())
            ->select(['id','title','cover_img','intro','start_time','end_time'])->paginate();
        foreach ($data as &$item){
            $collect_status = Collect::where('type',2)
                                        ->where('resource_id',$item->id)
                ->value('status');
            $item->collect_status = $collect_status ? $collect_status : 0;
        }
        return success(new ExamPageResource($data));
    }

    /**
     * 获取下一题
     * @param Request $request
     * @return mixed
     */
    public function getNextQuestion(Request $request)
    {
        $exam_id = $request->exam_id;
        $exam_question_id = $request->exam_question_id;
        $data = ExamService::getNextQuestion($exam_id,$exam_question_id);
        $data['user_exam_id'] = UserExam::where('exam_id',$exam_id)->where('user_id',$this->user_id)
            ->orderByDesc('id')->value('id');
        $data['minute'] =  $continue_time = Exam::where('id',$exam_id)->value('minute');
        return success(new ExamQuestionDetailResource($data));
    }

    /**
     * 提交单题答案
     * @param Request $request
     */
    public function commitQuestion(Request $request)
    {
        $exam_id = $request->exam_id;
        $answer = $request->answer;
        $user_exam_id = $request->user_exam_id;
        $question_id = $request->question_id;

        $question = Question::where('id',$question_id)->first();
        $userExamLog = ExamLog::where('user_exam_id',$user_exam_id)->where('question_id',$question_id)->first();
        if($userExamLog){
            $userExamLog->answer = $answer;
            if($answer == $question['answer']){
                $userExamLog->correct = 1;
                $userExamLog->score = $question['score'];
            }else{
                $userExamLog->correct = 2;
                $userExamLog->score = 0;
            }
            $userExamLog->save();
        }else{
            $exam_log['answer'] = $answer;
            $exam_log['user_exam_id'] = $user_exam_id;
            $exam_log['user_id'] = $this->user_id;
            $exam_log['exam_id'] = $exam_id;
            $exam_log['question_id'] = $question_id;
            $answer = explode(',',$answer);
            $exam_log['correct'] = 2;
            if($answer == $question['answer']){
                $exam_log['correct'] = 1;
                $exam_log['score'] = $question['score'];
            }
            ExamLog::create($exam_log);
        }
        return success([],'提交成功');
    }

    /**
     * 交卷
     * @param Request $request
     */
    public function commitExam(Request $request)
    {
        $user_exam_id = $request->user_exam_id;
        $exam_id = $request->exam_id;
        $exam = Exam::where('id',$exam_id)->first();
        $user_exam = UserExam::where('id',$user_exam_id)->first();
        /*******计算得分*******/
        $user_exam->end_time = Carbon::now()->toDateTimeString();
        $continue_time = Carbon::parse(Carbon::now())->diffInMinutes($user_exam['start_time']);
        $user_exam->continue_time = $continue_time > $exam['minute'] ? $exam['minute'] : $continue_time;
        $user_exam->score = ExamService::calculate($user_exam_id);
        $user_exam->save();
        return success($user_exam);
    }

    /**
     * 获取得分
     * @param Request $request
     * @return mixed
     */
    public function getScore(Request $request)
    {
        $exam_id = $request->exam_id;
        $userExam = UserExam::where('exam_id',$exam_id)
            ->where('user_id',$this->user_id)
            ->orderByDesc('id')
            ->first();
        return success($userExam);
    }

    /**
     * 开始考试
     * @param Request $request
     * @return mixed
     */
    public function startExam(Request $request)
    {
        $exam_id = $request->exam_id;
        $user_exam = UserExam::where('exam_id',$exam_id)->where('user_id',$this->user_id)
            ->whereNull('end_time')
            ->orderByDesc('id')
            ->first();
        $continue_time = Exam::where('id',$exam_id)->value('minute');
        if(!$user_exam){
            /*******不存在未结束的考试*******/
            $params = [
                'exam_id'   => $exam_id,
                'user_id'   => $this->user_id,
                'start_time'    => date("Y-m-d H:i:s")
            ];
            $result = UserExam::create($params);
            if(!$result){
                return error('开始考试失败');
            }
            $user_exam_id = $result['id'];
        }else{
            $user_exam_id = $user_exam['id'];

            /********超过指定时间自动结束******/
            if(Carbon::parse(Carbon::now())->diffInMinutes($user_exam['start_time']) >= $continue_time){
                $user_exam->end_time = Carbon::now();
                $user_exam->continue_time = $continue_time;
                $user_exam->save();
                $params = [
                    'exam_id'   => $exam_id,
                    'user_id'   => $this->user_id,
                    'start_time'    => date("Y-m-d H:i:s"),
                    'is_lately' => 1
                ];
                $result = UserExam::create($params);
                if(!$result){
                    return error('开始考试失败');
                }

                /********更新最新记录*******/
                UserExam::where('is_lately',1)->where('user_id',$this->user_id)
                    ->where('exam_id',$exam_id)->where('id','!=',$result['id'])->update(['is_lately'=>2]);

                $user_exam_id = $result['id'];
            }
        }
        $data = ExamService::getNextQuestion($exam_id);
        $data['user_exam_id'] = $user_exam_id;
        $data['minute'] =  $continue_time = Exam::where('id',$exam_id)->value('minute');
        return success(new ExamQuestionDetailResource($data),'开始考试');
    }
}